package com.ronri.ams.task;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cz.nongyetongv5.R;
import com.ronri.CustomDialog;
import com.ronri.ams.SystemEnvironmental;
import com.ronri.ams.bean.filepostbean;
import com.ronri.ams.bean.sample_info;
import com.ronri.ams.bean.tb_sampleinfo;
import com.ronri.ams.sample.activity_form_sample;
import com.ronri.common.DateUtil;
import com.ronri.common.StringManager;
import com.ronri.common.WaitDialog;
import com.ronri.db.RemoteDataService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.cz.nongyetongv5.application.InitApplication.gSampleInfo;


/**
 * Created by Administrator on 2017/5/7.
 */

public class activity_sample_info_wait_upload extends com.ronri.ams.sample.abstract_activity {

    // 列表数据
    private List<Map<String, Object>> mItems = new ArrayList<Map<String, Object>>();

    private List<tb_sampleinfo> mlist = new ArrayList<>();

    private Context mContext = null;
    private int mTarget = -1;
//    private sample_info mSampleInfo = null;

    private String mEditId = "-1";
    private int mCurrentIndex = -1;
    private SimpleAdapterDetailWithEvent adapter = null;

    private String szSec = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.sample_info_wait_upload);
        Log.i("aaa", "activity_sample_info_wait_upload");
        mContext = this;
        setTitle("待上传样品", "");
        init();

        Bundle bundle = getIntent().getExtras();
        TextView textView = (TextView) findViewById(R.id.task_title);

        if (bundle != null) {
            String szJson = bundle.getString("data");
            Log.i("test","szJson-->"+szJson);
            mlist = JSON.parseArray(szJson, tb_sampleinfo.class);

            int i = 0;
            for (tb_sampleinfo item : mlist) {

                if (item.getStatus().equals("0") || item.getStatus() == null) {
                    JSONObject array = JSON.parseObject(item.getJson());
                    Map<String, Object> ii = new HashMap<String, Object>();

                    ii.put("dept", "" + item.getEntname());
                    if (array.containsKey("user_name")) {
                        ii.put("user", "" + array.get("user_name"));
                    } else {
                        ii.put("user", "");
                    }

                    ii.put("date", "" + item.getDtime());
                    ii.put("samplename", "" + item.getSamplename());
                    ii.put("id", item.getId());
                    ii.put("json", item.getJson());
                    ii.put("sampleimg", R.id.imgSamplePhoto);
                    ii.put("positon", i);

                    mItems.add(ii);
                }

                i++;
            }

            String szTitle = bundle.getString("title");
            textView.setText(szTitle);
        }

        // 加载列表视图控件
        ListView listView = (ListView) findViewById(R.id.list_sample_info_wait_upload);

        // Item适配器
        adapter = new SimpleAdapterDetailWithEvent(
                this,
                R.layout.v_sample_wait_upload,
                mItems,
                new int[]{R.id.bt_do_sample, R.id.bt_delete_sample, R.id.bt_update_sample},
                new OnControlClickEvent() {
                    @Override
                    public void OnClick(View view, int Target) {
                        if (view instanceof Button) {

                            int nBtn = ((Button) view).getId();//.getText().toString();
                            mTarget = Target;
                            String json = mItems.get(Target).get("json").toString();
                            gSampleInfo = JSON.parseObject(json, sample_info.class);

                            if (nBtn == R.id.bt_do_sample) {
                                if (Target < mItems.size()) {
                                    mCurrentIndex = Target;
                                    mEditId = mItems.get(Target).get("id").toString();

                                    if (gSampleInfo != null) {
                                        Intent intent = new Intent(getApplicationContext(), activity_form_sample.class);
                                        Bundle bundle = new Bundle();
                                        bundle.putString("data", json);
                                        bundle.putInt("id", 1);
                                        intent.putExtras(bundle);
                                        startActivityForResult(intent, SystemEnvironmental.Sample_MAIN);
                                    }
                                }
                            }

                            if (nBtn == R.id.bt_delete_sample) {
                                CustomDialog.Builder builder = new CustomDialog.Builder(mContext);
                                builder.setMessage("确定删除记录吗？");
                                builder.setTitle("信息提示");
                                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        tb_sampleinfo info = mlist.get(mTarget);
                                        info.delete(info.getId());
                                        dialog.dismiss();

                                        Intent intent = new Intent();
                                        Bundle bundle = new Bundle();
                                        bundle.putBoolean("delete", true);
                                        intent.putExtras(bundle);
                                        setResult(RESULT_OK, intent);

                                        finish();
                                    }
                                });
                                builder.setNegativeButton("取消",
                                        new android.content.DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int which) {
                                                dialog.dismiss();
                                            }
                                        });

                                builder.create().show();
                            }

                            if (nBtn == R.id.bt_update_sample) {
                                CustomDialog.Builder builder = new CustomDialog.Builder(mContext);
                                builder.setMessage("确认上传记录吗？");
                                builder.setTitle("信息提示");
                                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        tb_sampleinfo info = mlist.get(mTarget);

                                        if (info == null)
                                            return;

                                        if (StringManager.isEmpty(info.getJson())) {
                                            return;
                                        }

                                        if(gSampleInfo.getSample_sign().size()<1||gSampleInfo.getSample_attach().size()<1){
                                            dialog.dismiss();
                                            Toast.makeText(mContext,"请填写完全部字段", Toast.LENGTH_SHORT).show();
                                            return;
                                        }

                                        List<String> lFiles = new ArrayList<>();

                                        // 转换
//                                        mSampleInfo = gSampleInfo;

                                        // 判断用户是否选择了2个
                                        if (StringManager.InitString(gSampleInfo.getSample_user()).indexOf(",") == -1) {
                                            dialog.dismiss();

                                            CustomDialog.Builder builder = new CustomDialog.Builder(mContext);
                                            builder.setMessage("抽样人员至少需要2人，请继续编辑...");
                                            builder.setTitle("信息提示");
                                            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                                public void onClick(DialogInterface dialog, int which) {
                                                    dialog.dismiss();
                                                }
                                            });

                                            builder.create().show();
                                            return;
                                        }

                                        // 组合上传照片，并合并到目标里去
                                        for (sample_info.SampleAttachBean item : gSampleInfo.getSample_attach()) {
                                            lFiles.add(item.getAttach_name());
                                        }

                                        // 组合上传照片，并合并到目标里去
                                        for (sample_info.SampleSignBean item : gSampleInfo.getSample_sign()) {
                                            lFiles.add(item.getAttach_name());
                                        }

                                        // 组合上传照片，并合并到目标里去
                                        for (sample_info.SampleBreedBean item : gSampleInfo.getSample_breed()) {
                                            for (sample_info.SampleBreedBean.BreedAttachBean ii : item.getBreed_attach()) {
                                                lFiles.add(ii.getAttach_name());
                                            }
                                        }

                                        RemoteDataService rdb = new RemoteDataService();
                                        rdb.postMFileToRemote("http://120.55.93.238:8080/ams/api/uploadPhoto.json", lFiles, null, new RemoteDataService.OnRemoteDataEvent() {
                                            //                                        rdb.postMFileToRemote("http://192.168.0.77:8080/ams/api/uploadPhoto.json", lFiles, null, new RemoteDataService.OnRemoteDataEvent() {
                                            @Override
                                            public void OnResultEvent(String szString) {
                                                try {
                                                    filepostbean bean = JSON.parseObject(szString, filepostbean.class);

                                                    if (bean.isSuccess()) {
                                                        for (filepostbean.DataBean item : bean.getData()) {

                                                            // 组合上传照片，并合并到目标里去
                                                            if (gSampleInfo.getSample_attach() != null)
                                                                for (sample_info.SampleAttachBean photo : gSampleInfo.getSample_attach()) {
                                                                    if (StringManager.InitString(photo.getAttach_name()).indexOf(item.getName()) != -1) {
                                                                        photo.setAttach_url(item.getUrl());
                                                                    }
                                                                }
                                                            // 组合上传照片，并合并到目标里去
                                                            if (gSampleInfo.getSample_sign() != null)
                                                                for (sample_info.SampleSignBean photo : gSampleInfo.getSample_sign()) {
                                                                    if (StringManager.InitString(photo.getAttach_name()).indexOf(item.getName()) != -1) {
                                                                        photo.setAttach_url(item.getUrl());
                                                                    }
                                                                }

                                                            // 组合上传照片，并合并到目标里去
                                                            if (gSampleInfo.getSample_breed() != null)
                                                                for (sample_info.SampleBreedBean photo : gSampleInfo.getSample_breed()) {
                                                                    for (sample_info.SampleBreedBean.BreedAttachBean ii : photo.getBreed_attach()) {
                                                                        if (StringManager.InitString(ii.getAttach_name()).indexOf(item.getName()) != -1) {
                                                                            ii.setAttach_url(item.getUrl());
                                                                        }
                                                                    }
                                                                }
                                                        }
                                                    }

                                                    String szJson = JSON.toJSONString(gSampleInfo);

                                                    RemoteDataService rrr = new RemoteDataService();

                                                    rrr.getRemoteData("http://120.55.93.238:8080/ams/api/uploadSample.json", szJson, "POST", new RemoteDataService.OnRemoteDataEvent() {
                                                        //                                                    rrr.getRemoteData(" http://192.168.0.77:8080/ams/api/uploadSample.json", szJson, "POST", new RemoteDataService.OnRemoteDataEvent() {
                                                        @Override
                                                        public void OnResultEvent(String szString) {
                                                            if (szString.equals("网络链接失败")) {
                                                                return;
                                                            }

                                                            JSONObject jsonObject = JSON.parseObject(szString);

                                                            if (jsonObject.getBoolean("success")) {
                                                                int nid = mlist.get(mTarget).getId();
                                                                mlist.get(mTarget).setStatus("1");
                                                                mlist.get(mTarget).update(nid);
                                                                Toast.makeText(mContext, "数据上传成功！", Toast.LENGTH_LONG);

                                                                Intent intent = new Intent();
                                                                Bundle bundle = new Bundle();
                                                                bundle.putBoolean("delete", true);
                                                                intent.putExtras(bundle);
                                                                setResult(RESULT_OK, intent);

                                                                finish();
                                                            } else {
                                                                CustomDialog.Builder builder = new CustomDialog.Builder(mContext);
                                                                builder.setMessage(jsonObject.getString("message"));
                                                                builder.setTitle("信息提示");
                                                                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                                                    public void onClick(DialogInterface dialog, int which) {
                                                                        dialog.dismiss();
                                                                    }
                                                                });

                                                                builder.create().show();
                                                            }
                                                        }

                                                        @Override
                                                        public void OnRuningState(int nStatus) {
                                                            if (nStatus == SystemEnvironmental.StartGetDataFromServer) {
                                                                WaitDialog.ShowDialog(mContext, "正在上传数据，请稍后...");
                                                            } else {
                                                                WaitDialog.HideDialog();
                                                            }
                                                        }

                                                        @Override
                                                        public String OnGetCustomParam() {
                                                            return null;
                                                        }
                                                    });
                                                } catch (Exception ex) {
                                                    CustomDialog.Builder builder = new CustomDialog.Builder(mContext);
                                                    builder.setMessage(szString);
                                                    builder.setTitle("信息提示");
                                                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                                        public void onClick(DialogInterface dialog, int which) {
                                                            dialog.dismiss();
                                                        }
                                                    });

                                                    builder.create().show();
                                                }
                                            }

                                            @Override
                                            public void OnRuningState(int nStatus) {
                                                if (nStatus == SystemEnvironmental.StartGetDataFromServer) {
                                                    WaitDialog.ShowDialog(mContext, "正在上传记录附件，请稍后...");
                                                } else {
                                                    WaitDialog.HideDialog();
                                                }
                                            }

                                            @Override
                                            public String OnGetCustomParam() {
                                                return null;
                                            }
                                        });

                                        dialog.dismiss();
                                    }
                                });
                                builder.setNegativeButton("取消",
                                        new android.content.DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int which) {
                                                dialog.dismiss();
                                            }
                                        });

                                builder.create().show();
                            }
                        }
                    }
                });

        // ListView绑定适配器
        listView.setAdapter(adapter);

        if (mItems.size() <= 0)
            ShowNoData(true);
        else
            ShowNoData(false);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == SystemEnvironmental.Sample_MAIN) {
                if (data != null) {
                    if (mEditId != "-1") {
                        String szJson = JSON.toJSONString(gSampleInfo);
                        tb_sampleinfo sinfo = new tb_sampleinfo();
                        sinfo.setId(Integer.parseInt(mEditId));
                        sinfo.setPid(gSampleInfo.getProject_id());
                        sinfo.setTid(gSampleInfo.getTask_id());
                        sinfo.setDtime(DateUtil.getCurrentDate("yyyy-MM-dd HH:mm:ss"));
                        sinfo.setEntname(gSampleInfo.getInspectd_name());
                        sinfo.setStatus("0");
                        sinfo.setHumen(gSampleInfo.getSample_user());
                        sinfo.setTname(gSampleInfo.getTask_name());
                        sinfo.setPid(gSampleInfo.getProject_id());
                        sinfo.setPname(gSampleInfo.getProject_name());
                        sinfo.setSamplename(gSampleInfo.GetSamplebreed());
                        sinfo.setJson(szJson);

                        sinfo.update(Integer.parseInt(mEditId));
                        mItems.get(mCurrentIndex).put("json", szJson);
                        mItems.get(mCurrentIndex).put("user", gSampleInfo.getUser_name());
                        mItems.get(mCurrentIndex).put("dept", gSampleInfo.getInspectd_name());
                        mItems.get(mCurrentIndex).put("samplename", gSampleInfo.GetSamplebreed());
                        adapter.notifyDataSetChanged();
                    }
                }
            }
        }
    }

    /***
     * 创建演示数据
     */
    private void CreateDemo() {
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.home);

        Map<String, Object> obj = new HashMap<String, Object>();

        obj.put("dept", "盐城市盐都区王宏林家庭农场");
        obj.put("user", "吴冬梅,李鑫");
        obj.put("date", "2017-01-08");
        obj.put("samplename", "青椒");
        obj.put("sampleimg", bitmap);

        mItems.add(obj);

        obj = new HashMap<String, Object>();

        obj.put("dept", "盐城市盐都区千秋果蔬专业合作社");
        obj.put("user", "吴冬梅,李鑫");
        obj.put("date", "2017-01-08");
        obj.put("samplename", "大白菜、蔬菜");
        obj.put("sampleimg", bitmap);

        mItems.add(obj);
    }

    /***
     * 显示未找到数据
     *
     * @param bShow
     */
    private void ShowNoData(boolean bShow) {
        RelativeLayout rr = (RelativeLayout) findViewById(R.id.vNoData);
        if (rr != null) {
            if (bShow == true) {
                rr.setVisibility(View.VISIBLE);
            } else {
                rr.setVisibility(View.GONE);
            }
        }
    }
}
